package com.example.wxback.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.wxback.model.MessageInfo;
import com.example.wxback.model.UserInfo;
import com.example.wxback.push.PushUtil;
import com.example.wxback.service.UserMessageDetailService;
import com.example.wxback.service.UserMessageService;
import com.example.wxback.service.WxUserService;
import com.example.wxback.util.CommonUtil;
import com.example.wxback.util.StringTools;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wx/message")
public class UserMessageController {

    @Autowired
    WxUserService wxUserService;

    @Autowired
    UserMessageService userMessageService;

    @Autowired
    UserMessageDetailService userMessageDetailService;

    @PostMapping("/upload")
    public JSONObject uploadMessage(@RequestBody MessageInfo messageInfo) {
        MessageInfo messageInfoTemp = userMessageService.getMessage(messageInfo);
        messageInfo.setCreateDate(new Date());
        if (messageInfoTemp == null) {
            userMessageService.insertMessage(messageInfo);
        } else {
            messageInfo.setUpdateDate(new Date());
            userMessageService.updateMessage(messageInfo);
        }
        messageInfoTemp = userMessageService.getMessage(messageInfo);
        if (messageInfoTemp != null) {
            messageInfo.setConversationId(messageInfoTemp.getId());
        }
        try {
            PushUtil.sendAndroidCustomizedcast(messageInfo.getUserId() + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userMessageDetailService.insertMessage(messageInfo)) {
            return CommonUtil.successJson("添加成功");
        } else {
            return CommonUtil.errorJson("消息添加失败");
        }
    }

    @GetMapping("/menu")
    public JSONObject getMessageMenuList(@Param("masterId") Integer masterId) {
        UserInfo userInfo = wxUserService.getUser(masterId);
        if (StringTools.isNullOrEmpty(userInfo)) {
            return CommonUtil.errorJson("用户不存在");
        }
        List<MessageInfo> messageInfoList = userMessageService.getMessageList(masterId);
        return CommonUtil.successJson(messageInfoList);
    }

    @GetMapping("/list")
    public JSONObject getMessageDetailList(@Param("conversationId") Integer conversationId) {
        List<MessageInfo> messageInfoList = userMessageDetailService.getMessageList(conversationId);
        return CommonUtil.successJson(messageInfoList);
    }
}
